package com.north.light.libmediatemplate.widget.touch

import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintSet
import com.north.light.libmediatemplate.utils.KtLogUtil

/**
 * FileName: TemplateTouchRootView
 * Author: lzt
 * Date: 2023/7/10 15:47
 * Description:触摸事件跟布局
 */
class TemplateTouchRootView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : ConstraintLayout(context, attrs) {


    private val DEFAULT_WIDTH = 200
    private val DEFAULT_HEIGHT = 200

    /**
     * 添加图片控件
     * */
    fun addChildView(img: View?) {
        val id = img?.id ?: return
        if (id == View.NO_ID || getId() == View.NO_ID) {
            return
        }
        addView(img)
        val set = ConstraintSet()
        //动态设置约束布局
        set.clone(this)
        set.connect(id, ConstraintSet.TOP, getId(), ConstraintSet.TOP)
        set.connect(id, ConstraintSet.START, getId(), ConstraintSet.START)
        KtLogUtil.d("addTouchImageView width: " + img.width)
        if (img.width == 0) {
            set.constrainWidth(id, DEFAULT_WIDTH)
        }
        if (img.height == 0) {
            set.constrainHeight(id, DEFAULT_HEIGHT)
        }
        set.applyTo(this)
    }


    /**
     * 移除图片控件
     * */
    fun removeChildView(img: View?) {
        removeView(img ?: return)
    }

    /**
     * 更新某个控件能否进行事件分发
     * */
    fun updateViewCanMove(img: View?, canMove: Boolean) {
        if (img is TemplateTouchImageView) {
            img.canMoveView(canMove)
        }
    }

    /**
     * 禁用所有控件的拖拽事件
     * */
    fun enableMoveEvent(canMove: Boolean) {
        val childCount = childCount
        for (count in 0 until childCount) {
            val childView = getChildAt(0)

            if (childView is TemplateTouchImageView) {
                childView.canMoveView(canMove)
            }
        }
    }


}